import React, { useState, useEffect } from 'react';
import { Table, Button, Modal, Form, Input, Select, message, Space, Tag, InputNumber, DatePicker } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, EyeOutlined, PlayCircleOutlined, PauseCircleOutlined } from '@ant-design/icons';

const { Option } = Select;
const { TextArea } = Input;

const StrategyList = () => {
  const [strategies, setStrategies] = useState([]);
  const [loading, setLoading] = useState(false);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [editingStrategy, setEditingStrategy] = useState(null);
  const [form] = Form.useForm();

  // 模拟数据
  const mockStrategies = [
    { 
      id: 1, 
      name: '价值成长混合策略', 
      type: '混合策略', 
      status: 'running',
      riskLevel: 'medium',
      targetReturn: 0.15,
      maxDrawdown: 0.10,
      description: '结合价值投资和成长投资的混合策略',
      factors: ['价值因子', '动量因子', '规模因子'],
      createTime: '2024-01-15',
      lastUpdate: '2024-01-20'
    },
    { 
      id: 2, 
      name: '量化择时策略', 
      type: '择时策略', 
      status: 'stopped',
      riskLevel: 'high',
      targetReturn: 0.20,
      maxDrawdown: 0.15,
      description: '基于技术指标的量化择时策略',
      factors: ['动量因子', '波动率因子'],
      createTime: '2024-01-10',
      lastUpdate: '2024-01-18'
    },
    { 
      id: 3, 
      name: '低风险稳健策略', 
      type: '稳健策略', 
      status: 'running',
      riskLevel: 'low',
      targetReturn: 0.08,
      maxDrawdown: 0.05,
      description: '低风险稳健型投资策略',
      factors: ['价值因子', '质量因子'],
      createTime: '2024-01-05',
      lastUpdate: '2024-01-19'
    },
  ];

  useEffect(() => {
    const stored = localStorage.getItem('strategyListData');
    if (stored) {
      setStrategies(JSON.parse(stored));
    } else {
      setStrategies(mockStrategies);
    }
  }, []);

  const columns = [
    { 
      title: '策略名称', 
      dataIndex: 'name',
      key: 'name',
      width: 180,
    },
    { 
      title: '类型', 
      dataIndex: 'type',
      key: 'type',
      width: 120,
      render: (type) => <Tag color="blue">{type}</Tag>,
    },
    { 
      title: '风险等级', 
      dataIndex: 'riskLevel',
      key: 'riskLevel',
      width: 100,
      render: (level) => {
        const colors = { low: 'green', medium: 'orange', high: 'red' };
        const texts = { low: '低风险', medium: '中风险', high: '高风险' };
        return <Tag color={colors[level]}>{texts[level]}</Tag>;
      },
    },
    { 
      title: '目标收益', 
      dataIndex: 'targetReturn',
      key: 'targetReturn',
      width: 100,
      render: (return_) => `${(return_ * 100).toFixed(1)}%`,
    },
    { 
      title: '最大回撤', 
      dataIndex: 'maxDrawdown',
      key: 'maxDrawdown',
      width: 100,
      render: (drawdown) => `${(drawdown * 100).toFixed(1)}%`,
    },
    { 
      title: '状态', 
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status) => (
        <Tag color={status === 'running' ? 'green' : 'red'}>
          {status === 'running' ? '运行中' : '已停止'}
        </Tag>
      ),
    },
    { 
      title: '创建时间', 
      dataIndex: 'createTime',
      key: 'createTime',
      width: 120,
    },
    { 
      title: '操作', 
      key: 'action',
      width: 250,
      render: (_, record) => (
        <Space size="middle">
          <Button 
            type="link" 
            icon={<EyeOutlined />}
            onClick={() => handleViewDetails(record)}
          >
            详情
          </Button>
          <Button 
            type="link" 
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Button 
            type="link" 
            icon={record.status === 'running' ? <PauseCircleOutlined /> : <PlayCircleOutlined />}
            onClick={() => handleToggleStatus(record)}
          >
            {record.status === 'running' ? '停止' : '启动'}
          </Button>
          <Button 
            type="link" 
            danger 
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record.id)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  const handleAdd = () => {
    setEditingStrategy(null);
    form.resetFields();
    setIsModalVisible(true);
  };

  const handleEdit = (record) => {
    setEditingStrategy(record);
    form.setFieldsValue({
      ...record,
      targetReturn: record.targetReturn * 100,
      maxDrawdown: record.maxDrawdown * 100,
    });
    setIsModalVisible(true);
  };

  const handleDelete = (id) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这个策略吗？删除后无法恢复。',
      onOk: () => {
        const updatedStrategies = strategies.filter(strategy => strategy.id !== id);
        setStrategies(updatedStrategies);
        localStorage.setItem('strategyListData', JSON.stringify(updatedStrategies));
        message.success('删除成功');
      },
    });
  };

  const handleToggleStatus = (record) => {
    const newStatus = record.status === 'running' ? 'stopped' : 'running';
    const updatedStrategies = strategies.map(strategy => 
      strategy.id === record.id ? { ...strategy, status: newStatus } : strategy
    );
    setStrategies(updatedStrategies);
    localStorage.setItem('strategyListData', JSON.stringify(updatedStrategies));
    message.success(`策略已${newStatus === 'running' ? '启动' : '停止'}`);
  };

  const handleViewDetails = (record) => {
    Modal.info({
      title: '策略详情',
      width: 600,
      content: (
        <div>
          <p><strong>策略名称：</strong>{record.name}</p>
          <p><strong>策略类型：</strong>{record.type}</p>
          <p><strong>风险等级：</strong>{record.riskLevel === 'low' ? '低风险' : record.riskLevel === 'medium' ? '中风险' : '高风险'}</p>
          <p><strong>目标收益：</strong>{(record.targetReturn * 100).toFixed(1)}%</p>
          <p><strong>最大回撤：</strong>{(record.maxDrawdown * 100).toFixed(1)}%</p>
          <p><strong>策略状态：</strong>{record.status === 'running' ? '运行中' : '已停止'}</p>
          <p><strong>策略描述：</strong>{record.description}</p>
          <p><strong>使用因子：</strong>{record.factors.join(', ')}</p>
          <p><strong>创建时间：</strong>{record.createTime}</p>
          <p><strong>最后更新：</strong>{record.lastUpdate}</p>
        </div>
      ),
    });
  };

  const handleModalOk = async () => {
    try {
      const values = await form.validateFields();
      const strategyData = {
        ...values,
        targetReturn: values.targetReturn / 100, // 转换为小数
        maxDrawdown: values.maxDrawdown / 100, // 转换为小数
        factors: values.factors || [],
        createTime: new Date().toISOString().split('T')[0],
        lastUpdate: new Date().toISOString().split('T')[0],
      };

      if (editingStrategy) {
        // 编辑模式
        const updatedStrategies = strategies.map(strategy => 
          strategy.id === editingStrategy.id ? { ...strategy, ...strategyData } : strategy
        );
        setStrategies(updatedStrategies);
        localStorage.setItem('strategyListData', JSON.stringify(updatedStrategies));
        message.success('策略更新成功');
      } else {
        // 新增模式
        const newStrategy = {
          id: Date.now(),
          ...strategyData,
          status: 'stopped',
        };
        const updatedStrategies = [...strategies, newStrategy];
        setStrategies(updatedStrategies);
        localStorage.setItem('strategyListData', JSON.stringify(updatedStrategies));
        message.success('策略创建成功');
      }
      
      setIsModalVisible(false);
    } catch (error) {
      console.error('表单验证失败:', error);
    }
  };

  const handleModalCancel = () => {
    setIsModalVisible(false);
  };

  return (
    <div style={{ padding: '24px' }}>
      <div style={{ marginBottom: '16px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <h2>策略管理</h2>
        <Button 
          type="primary" 
          icon={<PlusOutlined />}
          onClick={handleAdd}
        >
          新建策略
        </Button>
      </div>

      <Table 
        dataSource={strategies} 
        columns={columns} 
        rowKey="id"
        loading={loading}
        pagination={{
          total: strategies.length,
          pageSize: 10,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条/共 ${total} 条`,
        }}
      />

      <Modal
        title={editingStrategy ? '编辑策略' : '新建策略'}
        open={isModalVisible}
        onOk={handleModalOk}
        onCancel={handleModalCancel}
        width={600}
        destroyOnClose
      >
        <Form
          form={form}
          layout="vertical"
          initialValues={{ 
            riskLevel: 'medium', 
            targetReturn: 15, 
            maxDrawdown: 10,
            factors: []
          }}
        >
          <Form.Item
            name="name"
            label="策略名称"
            rules={[{ required: true, message: '请输入策略名称' }]}
          >
            <Input placeholder="请输入策略名称" />
          </Form.Item>

          <Form.Item
            name="type"
            label="策略类型"
            rules={[{ required: true, message: '请选择策略类型' }]}
          >
            <Select placeholder="请选择策略类型">
              <Option value="混合策略">混合策略</Option>
              <Option value="择时策略">择时策略</Option>
              <Option value="稳健策略">稳健策略</Option>
              <Option value="成长策略">成长策略</Option>
              <Option value="价值策略">价值策略</Option>
            </Select>
          </Form.Item>

          <Form.Item
            name="riskLevel"
            label="风险等级"
            rules={[{ required: true, message: '请选择风险等级' }]}
          >
            <Select placeholder="请选择风险等级">
              <Option value="low">低风险</Option>
              <Option value="medium">中风险</Option>
              <Option value="high">高风险</Option>
            </Select>
          </Form.Item>

          <Form.Item
            name="targetReturn"
            label="目标收益 (%)"
            rules={[{ required: true, message: '请输入目标收益' }]}
          >
            <InputNumber
              min={0}
              max={100}
              placeholder="请输入目标收益百分比"
              style={{ width: '100%' }}
            />
          </Form.Item>

          <Form.Item
            name="maxDrawdown"
            label="最大回撤 (%)"
            rules={[{ required: true, message: '请输入最大回撤' }]}
          >
            <InputNumber
              min={0}
              max={100}
              placeholder="请输入最大回撤百分比"
              style={{ width: '100%' }}
            />
          </Form.Item>

          <Form.Item
            name="factors"
            label="使用因子"
          >
            <Select
              mode="multiple"
              placeholder="请选择使用的因子"
              style={{ width: '100%' }}
            >
              <Option value="价值因子">价值因子</Option>
              <Option value="动量因子">动量因子</Option>
              <Option value="规模因子">规模因子</Option>
              <Option value="质量因子">质量因子</Option>
              <Option value="波动率因子">波动率因子</Option>
              <Option value="成长因子">成长因子</Option>
            </Select>
          </Form.Item>

          <Form.Item
            name="description"
            label="策略描述"
            rules={[{ required: true, message: '请输入策略描述' }]}
          >
            <TextArea 
              rows={4}
              placeholder="请输入策略描述"
            />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default StrategyList; 